package cn.topcodes.tcsf.wechat.service;

import cn.topcode.unicorn.utils.DynamicQueryUtil;
import cn.topcode.unicorn.utils.StringUtil;
import cn.topcodes.tcsf.admin.commons.domain.Page;
import cn.topcodes.tcsf.admin.commons.generic.GenericService;
import cn.topcodes.tcsf.wechat.domain.entity.WechatPushLog;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = false, rollbackFor = Exception.class)
public class WechatPushLogServiceImpl extends GenericService<WechatPushLog> implements WechatPushLogService {

    @Override
    public Page<WechatPushLog> findPage(Map<String, String[]> searchParams, int pageNumber, int pageSize) {
        searchParams = searchParams == null ? new HashMap() : searchParams;
        pageNumber = pageNumber < 1 ? 1 : pageNumber;
        pageSize = pageSize < 1 ? 1 : pageSize;
        Example example = this.buildExample();
        if (!searchParams.isEmpty()) {
            Example.Criteria criteria = example.createCriteria();
            String[] startTime = searchParams.get("startTime");
            String[] endTime = searchParams.get("endTime");
            String[] state = searchParams.get("state");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            if (startTime != null && startTime.length > 0
                    && StringUtil.isNotBlank(startTime[0])) {
                criteria.andGreaterThanOrEqualTo("time", LocalDateTime.parse(startTime[0], formatter));
            }
            if (endTime != null && endTime.length > 0
                    && StringUtil.isNotBlank(endTime[0])) {
                criteria.andLessThanOrEqualTo("time", LocalDateTime.parse(endTime[0], formatter));
            }
            if (state != null && state.length > 0
                    && StringUtil.isNotBlank(state[0])) {
                if (!WechatPushLog.TYPE_ALL.equals(state[0])) {
                    criteria.andEqualTo("state", state[0]);
                }
            }
        }
        DynamicQueryUtil.convert(searchParams, example);
        return this.findPage(example, pageNumber, pageSize);
    }
}
